<template>
  <div>
    <!-- 查询，增加 -->
    <el-card>
      <el-form :inline="true" :model="params">
        <el-form-item label="商品名称">
          <el-input
            v-model="params.name"
            placeholder="按商品名称查找"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList(1)" icon="el-icon-search"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="add" icon="el-icon-plus"
            >增加</el-button
          >
          <el-button type="danger" @click="removeMore" icon="el-icon-delete"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 表格 -->
    <el-card>
      <el-table
        :data="rows"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="商品名称"> </el-table-column>
        <el-table-column prop="brandId" label="品牌"> </el-table-column>
        <el-table-column prop="imgs" label="轮播图片">
          <template slot-scope="scope">
            <img
              style="width: 40px; height: 40px"
              v-if="scope.row.imgs"
              :src="scope.row.imgs"
            />
          </template>
        </el-table-column>

        <el-table-column prop="sales" label="销量"></el-table-column>
        <el-table-column prop="status" label="上架">
          <template slot-scope="scope">
            <el-checkbox
              v-model="scope.row.status"
              @change="statusChange(scope.row)"
              :true-label="1"
              :false-label="0"
            >
            </el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="详情"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              style="margin-bottom: 10px"
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除此数据吗？"
              @confirm="remove(scope.row)"
            >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-refresh-right"
                slot="reference"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="SizeChange"
          @current-change="getList"
          :current-page="params.pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <el-dialog
      :name="form._id ? '修改' : '新增'"
      :visible.sync="dialogFormVisible"
      width="400px"
    >
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input type="text" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-input type="text" v-model="form.brandId"></el-input>
        </el-form-item>
        <el-form-item label="轮播图片" prop="imgs">
          <div
            @click="openFile"
            style="
              overflow: hidden;
              width: 100px;
              height: 100px;
              font-size: 32px;
              border: 1px dashed #ccc;
              text-align: center;
              line-height: 100px;
            "
          >
            <img
              style="max-width: 100%; max-height: 100%"
              v-if="form.imgs"
              :src="form.imgs"
            />
            <span v-else>+</span>
          </div>
          <input
            ref="file"
            style="display: none"
            multiple
            accept="image/*"
            type="file"
            @change="changeFile"
          />
        </el-form-item>

        <el-form-item label="销量" prop="sales">
          <el-input-number type="text" v-model="form.sales"></el-input-number>
        </el-form-item>
        <el-form-item label="详情" prop="description">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from "@/api";

export default {
  components: {},
  data() {
    return {
      ///查询参数
      params: {
        name: "",
        pageNum: 1,
        pageSize: 5,
      },
      rows: [],
      total: 0,
      dialogFormVisible: false,
      form: {
        _id: 0,
        name: "",
        brandId: "",
        imgs: "",
        sales: "",
        description: "",
      },
      rules: {
        imgs: [{ required: true, message: "图片不能为空", trugger: "blur" }],
      },
      selecteds: [],
    };
  },
  methods: {
    //获取列表
    getList(pageNum) {
      if (pageNum) this.params.pageNum = pageNum;
      this.$http({
        url: "/admin/product",
        params: this.params,
      }).then((res) => {
        this.total = res.total;
        this.rows = res.rows;
      });
    },

    //启用停用
    statusChange(row) {
      this.$http({
        url: "/admin/product",
        method: "PUT",
        data: {
          indexId: row._id,
          status: row.status,
        },
      }).then((res) => {
        if (res.errorMsg) {
          this.getList();
        }
      });
    },

    //修改pageSize
    SizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.getList(1);
    },
    add() {
      //初始化
      this.form = {
        _id: 0,
        imgs: "",
        name: "",
        brandId: "",
        sales: "",
      };
      this.dialogFormVisible = true;
    },

    //修改数据
    edit(row) {
      this.form = row;
      this.dialogFormVisible = true;
    },

    openFile() {
      let fileElement = this.$refs.file;
      fileElement.click();
    },
    changeFile(e) {
      let files = e.target.files;
      let formData = new FormData();
      formData.append("file", files[0]);
      this.$http({
        url: "/upload",
        method: "POST",
        data: formData,
      }).then((res) => {
        if (res.path) this.form.img = api.baseURL + "/" + res.path;
      });
    },

    //删除数据
    remove(row) {
      this.$http({
        url: "/admin/product",
        method: "DELETE",
        params: { indexId: row._id },
      }).then((res) => {
        if (!res.errorMsg) {
          this.getList(1);
        }
      });
    },
    handleSelectionChange(rows) {
      //存储选中数据
      this.selecteds = rows;
    },

    //批量删除
    removeMore() {
      //获取被选中的数据
      let checkedRowsPrmose = [];
      let success = [],
        fail = [];
      for (let i = 0; i < this.selecteds.length; i++) {
        checkedRowsPrmose.push(
          new Promise((resovle) => {
            let row = this.selecteds[i];
            this.$http({
              url: "/admin/product",
              method: "DELETE",
              params: { indexId: row._id },
            }).then((res) => {
              if (!res.errorMsg) {
                success.push(row._id);
              } else {
                fail.push(row._id);
              }
              resovle();
            });
          })
        );
      }
      this.$confirm("此操作将删除选中的数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //删除数据
        Promise.all(checkedRowsPrmose).then(() => {
          this.$message({
            message: `批量删除完成，成功删除${success.length}条数据，删除失败${fail.length}条数据`,
            duration: 3000,
          });
          this.getList(1);
        });
      });
    },

    //新增数据
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.indexId = this.form._id;
          this.$http({
            url: "/admin/product",
            method: this.form.indexId ? "PUT" : "POST", //通过indexId判断是新增还是修改
            data: this.form,
          }).then((res) => {
            if (!res.errorMsg) {
              this.dialogFormVisible = false;
              this.getList(this.form.indexId ? undefined : 1);
            }
          });
        }
      });
    },
  },
  created() {
    this.getList();
    // this.$http("/admin/index/banners").then((banners) => {
    //   console.log(banners);
    // });
  },
  mouted() {},
};
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
.block {
  margin-top: 20px;
}
</style>